<?php
class PageController extends FrontController
{
	public function indexAction()
	{
		
	}
	
	public function loadAction()
	{
		$request = $this->getRequest();
		
		$count = $request->limit;
		$offset = $request->start;
		
		$select = new CF_Db_Select();
		$select->table(array('p' => '##_pages'), array('created_time'))
			->joinInner(array('pt' => '##_page_trans'), 'pt.page_id=p.id', array('page_id', 'name'))
			->where(new CF_Db_Expr('`lang_id`=%s', CF_Session::get('langId')))
			->limit($count, $offset);
		
		# check if search action
		$field = $request->field;
		$value = $request->value;
		
		if($field && $value){
			$value = CF_Db::getInstance()->escape($value);
			$where = "`$field` LIKE '%$value%'";
			$select->where($where);
		}
		
		$store = $select->execute();

		return array(
			'total' => $store->getFoundRows(),
			'rows' => $store->getAll()
		);
	}
	
	public function detailAction()
	{
		$pageIid = $this->getRequest()->page_id;
		$langId = CF_Session::get('langId');
		
		$tbPageTran = new Table_PageTrans();
		return array(
			'success' => true,
			'data'	=> $tbPageTran->detail($pageIid, $langId)
		);
	}
	
	public function addAction()
	{
		$tbPage = new Table_Page();
		
		$data = $this->getRequest()->getCollection('name', 'content');
		$result = $tbPage->insert($data);
		if(is_array($result)) $response = array('success' => true, 'data' => $result);
		else $response = array('error' => true, 'msg' => $result);
		return $response;
	}
	
	public function updateAction()
	{
		$tbPageTrans = new Table_PageTrans();
		$request = $this->getRequest();
		
		$pageId = $request->page_id;
		$data = $request->getCollectionIf('name', 'content');
		
		$where = new CF_Db_Expr(
			'`page_id`=%s AND lang_id=%s', $pageId, CF_Session::get('langId')
		);
		$row = $tbPageTrans->update($data, $where);
		
		return array('success' => is_numeric($row));
	}
	
	public function delAction()
	{
		$tbPage = new Table_Page();
		$tbPage->deleteById($this->getRequest()->ids);
		return array('success' => true);
	}
}